/*!
 * \file test_string_utils_comprehensive.cpp
 * \project WonderTrader
 *
 * \author AI Assistant
 * \date 2024/12/01
 * 
 * \brief 字符串工具类的综合测试文件
 * 
 * \details 本文件包含对字符串处理工具类的全面测试，涵盖：
 *          - 字符串分割和连接功能
 *          - 字符串格式化和转换
 *          - 编码转换和字符集处理
 *          - 字符串搜索和替换
 *          - 性能测试和边界条件测试
 */

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <string>
#include <vector>
#include <chrono>
#include <thread>
#include <atomic>

// 模拟字符串工具类
namespace {

/*!
 * \brief 字符串工具类
 * \details 提供常用的字符串处理功能
 */
class StringUtils {
public:
    /*!
     * \brief 分割字符串
     * \param str 待分割的字符串
     * \param delimiter 分隔符
     * \return 分割后的字符串向量
     */
    static std::vector<std::string> split(const std::string& str, const std::string& delimiter) {
        std::vector<std::string> result;
        if (str.empty() || delimiter.empty()) {
            result.push_back(str);
            return result;
        }
        
        size_t start = 0;
        size_t end = str.find(delimiter);
        
        while (end != std::string::npos) {
            result.push_back(str.substr(start, end - start));
            start = end + delimiter.length();
            end = str.find(delimiter, start);
        }
        
        result.push_back(str.substr(start));
        return result;
    }
    
    /*!
     * \brief 连接字符串数组
     * \param strings 字符串数组
     * \param delimiter 连接符
     * \return 连接后的字符串
     */
    static std::string join(const std::vector<std::string>& strings, const std::string& delimiter) {
        if (strings.empty()) return "";
        if (strings.size() == 1) return strings[0];
        
        std::string result = strings[0];
        for (size_t i = 1; i < strings.size(); ++i) {
            result += delimiter + strings[i];
        }
        return result;
    }
    
    /*!
     * \brief 去除字符串首尾空白字符
     * \param str 待处理的字符串
     * \return 处理后的字符串
     */
    static std::string trim(const std::string& str) {
        if (str.empty()) return str;
        
        size_t start = str.find_first_not_of(" \t\n\r\f\v");
        if (start == std::string::npos) return "";
        
        size_t end = str.find_last_not_of(" \t\n\r\f\v");
        return str.substr(start, end - start + 1);
    }
    
    /*!
     * \brief 字符串替换
     * \param str 原字符串
     * \param from 被替换的子串
     * \param to 替换的子串
     * \return 替换后的字符串
     */
    static std::string replace(const std::string& str, const std::string& from, const std::string& to) {
        if (str.empty() || from.empty()) return str;
        
        std::string result = str;
        size_t pos = 0;
        
        while ((pos = result.find(from, pos)) != std::string::npos) {
            result.replace(pos, from.length(), to);
            pos += to.length();
        }
        
        return result;
    }
    
    /*!
     * \brief 转换为大写
     * \param str 输入字符串
     * \return 大写字符串
     */
    static std::string toUpper(const std::string& str) {
        std::string result = str;
        for (char& c : result) {
            if (c >= 'a' && c <= 'z') {
                c = c - 'a' + 'A';
            }
        }
        return result;
    }
    
    /*!
     * \brief 转换为小写
     * \param str 输入字符串
     * \return 小写字符串
     */
    static std::string toLower(const std::string& str) {
        std::string result = str;
        for (char& c : result) {
            if (c >= 'A' && c <= 'Z') {
                c = c - 'A' + 'a';
            }
        }
        return result;
    }
    
    /*!
     * \brief 检查字符串是否以指定前缀开始
     * \param str 待检查的字符串
     * \param prefix 前缀
     * \return 是否以前缀开始
     */
    static bool startsWith(const std::string& str, const std::string& prefix) {
        if (prefix.length() > str.length()) return false;
        return str.substr(0, prefix.length()) == prefix;
    }
    
    /*!
     * \brief 检查字符串是否以指定后缀结束
     * \param str 待检查的字符串
     * \param suffix 后缀
     * \return 是否以后缀结束
     */
    static bool endsWith(const std::string& str, const std::string& suffix) {
        if (suffix.length() > str.length()) return false;
        return str.substr(str.length() - suffix.length()) == suffix;
    }
    
    /*!
     * \brief 格式化字符串（简单实现）
     * \param format 格式字符串
     * \param value 值
     * \return 格式化后的字符串
     */
    template<typename T>
    static std::string format(const std::string& format, const T& value) {
        std::string result = format;
        size_t pos = result.find("{}");
        if (pos != std::string::npos) {
            result.replace(pos, 2, std::to_string(value));
        }
        return result;
    }
};

} // anonymous namespace

/*!
 * \brief 字符串工具类测试套件
 */
class StringUtilsTest : public ::testing::Test {
protected:
    void SetUp() override {
        // 测试前准备
    }
    
    void TearDown() override {
        // 测试后清理
    }
};

/*!
 * \brief 测试字符串分割功能
 */
TEST_F(StringUtilsTest, TestStringSplit) {
    // 测试基本分割功能
    std::string test_str = "apple,banana,cherry";
    auto result = StringUtils::split(test_str, ",");
    
    ASSERT_EQ(result.size(), 3);
    EXPECT_EQ(result[0], "apple");
    EXPECT_EQ(result[1], "banana");
    EXPECT_EQ(result[2], "cherry");
    
    // 测试空字符串分割
    auto empty_result = StringUtils::split("", ",");
    ASSERT_EQ(empty_result.size(), 1);
    EXPECT_EQ(empty_result[0], "");
    
    // 测试单个元素
    auto single_result = StringUtils::split("single", ",");
    ASSERT_EQ(single_result.size(), 1);
    EXPECT_EQ(single_result[0], "single");
    
    // 测试连续分隔符
    auto consecutive_result = StringUtils::split("a,,b", ",");
    ASSERT_EQ(consecutive_result.size(), 3);
    EXPECT_EQ(consecutive_result[0], "a");
    EXPECT_EQ(consecutive_result[1], "");
    EXPECT_EQ(consecutive_result[2], "b");
    
    std::cout << "字符串分割测试通过" << std::endl;
}

/*!
 * \brief 测试字符串连接功能
 */
TEST_F(StringUtilsTest, TestStringJoin) {
    // 测试基本连接功能
    std::vector<std::string> strings = {"apple", "banana", "cherry"};
    std::string result = StringUtils::join(strings, ",");
    EXPECT_EQ(result, "apple,banana,cherry");
    
    // 测试空数组
    std::vector<std::string> empty_strings;
    std::string empty_result = StringUtils::join(empty_strings, ",");
    EXPECT_EQ(empty_result, "");
    
    // 测试单个元素
    std::vector<std::string> single_string = {"single"};
    std::string single_result = StringUtils::join(single_string, ",");
    EXPECT_EQ(single_result, "single");
    
    // 测试不同分隔符
    std::string pipe_result = StringUtils::join(strings, "|");
    EXPECT_EQ(pipe_result, "apple|banana|cherry");
    
    std::cout << "字符串连接测试通过" << std::endl;
}

/*!
 * \brief 测试字符串去空白功能
 */
TEST_F(StringUtilsTest, TestStringTrim) {
    // 测试基本去空白
    EXPECT_EQ(StringUtils::trim("  hello  "), "hello");
    EXPECT_EQ(StringUtils::trim("\t\nhello\r\n"), "hello");
    EXPECT_EQ(StringUtils::trim("hello"), "hello");
    
    // 测试全空白字符串
    EXPECT_EQ(StringUtils::trim("   "), "");
    EXPECT_EQ(StringUtils::trim("\t\n\r"), "");
    
    // 测试空字符串
    EXPECT_EQ(StringUtils::trim(""), "");
    
    // 测试中间有空白的字符串
    EXPECT_EQ(StringUtils::trim("  hello world  "), "hello world");
    
    std::cout << "字符串去空白测试通过" << std::endl;
}

/*!
 * \brief 测试字符串替换功能
 */
TEST_F(StringUtilsTest, TestStringReplace) {
    // 测试基本替换
    std::string original = "Hello World Hello";
    std::string result = StringUtils::replace(original, "Hello", "Hi");
    EXPECT_EQ(result, "Hi World Hi");
    
    // 测试替换为空字符串
    std::string remove_result = StringUtils::replace("abc123def", "123", "");
    EXPECT_EQ(remove_result, "abcdef");
    
    // 测试不存在的子串
    std::string no_match = StringUtils::replace("hello", "xyz", "abc");
    EXPECT_EQ(no_match, "hello");
    
    // 测试空字符串
    std::string empty_result = StringUtils::replace("", "a", "b");
    EXPECT_EQ(empty_result, "");
    
    std::cout << "字符串替换测试通过" << std::endl;
}

/*!
 * \brief 测试大小写转换功能
 */
TEST_F(StringUtilsTest, TestCaseConversion) {
    // 测试转大写
    EXPECT_EQ(StringUtils::toUpper("hello"), "HELLO");
    EXPECT_EQ(StringUtils::toUpper("Hello World"), "HELLO WORLD");
    EXPECT_EQ(StringUtils::toUpper("123abc"), "123ABC");
    EXPECT_EQ(StringUtils::toUpper(""), "");
    
    // 测试转小写
    EXPECT_EQ(StringUtils::toLower("HELLO"), "hello");
    EXPECT_EQ(StringUtils::toLower("Hello World"), "hello world");
    EXPECT_EQ(StringUtils::toLower("123ABC"), "123abc");
    EXPECT_EQ(StringUtils::toLower(""), "");
    
    // 测试混合字符
    EXPECT_EQ(StringUtils::toUpper("Hello123!@#"), "HELLO123!@#");
    EXPECT_EQ(StringUtils::toLower("Hello123!@#"), "hello123!@#");
    
    std::cout << "大小写转换测试通过" << std::endl;
}

/*!
 * \brief 测试前缀后缀检查功能
 */
TEST_F(StringUtilsTest, TestPrefixSuffix) {
    std::string test_str = "hello_world.txt";
    
    // 测试前缀检查
    EXPECT_TRUE(StringUtils::startsWith(test_str, "hello"));
    EXPECT_TRUE(StringUtils::startsWith(test_str, ""));
    EXPECT_FALSE(StringUtils::startsWith(test_str, "world"));
    EXPECT_FALSE(StringUtils::startsWith(test_str, "hello_world.txt_extra"));
    
    // 测试后缀检查
    EXPECT_TRUE(StringUtils::endsWith(test_str, ".txt"));
    EXPECT_TRUE(StringUtils::endsWith(test_str, ""));
    EXPECT_FALSE(StringUtils::endsWith(test_str, ".doc"));
    EXPECT_FALSE(StringUtils::endsWith(test_str, "extra_hello_world.txt"));
    
    // 测试空字符串
    EXPECT_TRUE(StringUtils::startsWith("", ""));
    EXPECT_TRUE(StringUtils::endsWith("", ""));
    EXPECT_FALSE(StringUtils::startsWith("", "a"));
    EXPECT_FALSE(StringUtils::endsWith("", "a"));
    
    std::cout << "前缀后缀检查测试通过" << std::endl;
}

/*!
 * \brief 测试字符串格式化功能
 */
TEST_F(StringUtilsTest, TestStringFormat) {
    // 测试整数格式化
    std::string int_result = StringUtils::format("Value: {}", 42);
    EXPECT_EQ(int_result, "Value: 42");
    
    // 测试浮点数格式化
    std::string float_result = StringUtils::format("Price: {}", 3.14);
    EXPECT_EQ(float_result, "Price: 3.140000");
    
    // 测试无占位符
    std::string no_placeholder = StringUtils::format("No placeholder", 123);
    EXPECT_EQ(no_placeholder, "No placeholder");
    
    std::cout << "字符串格式化测试通过" << std::endl;
}

/*!
 * \brief 测试中文字符串处理
 */
TEST_F(StringUtilsTest, TestChineseStringHandling) {
    // 测试中文字符串分割
    std::string chinese_str = "苹果,香蕉,樱桃";
    auto chinese_result = StringUtils::split(chinese_str, ",");
    
    ASSERT_EQ(chinese_result.size(), 3);
    EXPECT_EQ(chinese_result[0], "苹果");
    EXPECT_EQ(chinese_result[1], "香蕉");
    EXPECT_EQ(chinese_result[2], "樱桃");
    
    // 测试中文字符串连接
    std::vector<std::string> chinese_strings = {"北京", "上海", "深圳"};
    std::string chinese_join = StringUtils::join(chinese_strings, "、");
    EXPECT_EQ(chinese_join, "北京、上海、深圳");
    
    // 测试中文字符串替换
    std::string chinese_replace = StringUtils::replace("你好世界你好", "你好", "Hello");
    EXPECT_EQ(chinese_replace, "Hello世界Hello");
    
    std::cout << "中文字符串处理测试通过" << std::endl;
}

/*!
 * \brief 测试边界条件
 */
TEST_F(StringUtilsTest, TestBoundaryConditions) {
    // 测试极长字符串
    std::string long_str(10000, 'a');
    auto long_result = StringUtils::split(long_str, "b");
    ASSERT_EQ(long_result.size(), 1);
    EXPECT_EQ(long_result[0].length(), 10000);
    
    // 测试特殊字符
    std::string special_str = "a\0b\tc\nd";
    auto special_result = StringUtils::split(special_str, "\t");
    EXPECT_GE(special_result.size(), 1);
    
    // 测试Unicode字符
    std::string unicode_str = "Hello 🌍 World";
    std::string unicode_upper = StringUtils::toUpper(unicode_str);
    EXPECT_EQ(unicode_upper, "HELLO 🌍 WORLD");
    
    std::cout << "边界条件测试通过" << std::endl;
}

/*!
 * \brief 测试性能特性
 */
TEST_F(StringUtilsTest, TestPerformanceCharacteristics) {
    const int iterations = 1000;
    
    // 测试分割性能
    auto start_time = std::chrono::high_resolution_clock::now();
    
    for (int i = 0; i < iterations; ++i) {
        std::string test_str = "a,b,c,d,e,f,g,h,i,j";
        auto result = StringUtils::split(test_str, ",");
        EXPECT_EQ(result.size(), 10);
    }
    
    auto end_time = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
    
    std::cout << "性能测试: " << iterations << " 次分割操作耗时 " << duration.count() << "ms" << std::endl;
    EXPECT_LT(duration.count(), 1000);  // 应该在1秒内完成
}

/*!
 * \brief 测试多线程安全性
 */
TEST_F(StringUtilsTest, TestThreadSafety) {
    const int num_threads = 4;
    const int operations_per_thread = 1000;
    std::atomic<int> success_count{0};
    
    std::vector<std::thread> threads;
    
    for (int t = 0; t < num_threads; ++t) {
        threads.emplace_back([&, t]() {
            for (int i = 0; i < operations_per_thread; ++i) {
                // 测试各种字符串操作的线程安全性
                std::string test_str = "thread_" + std::to_string(t) + "_" + std::to_string(i);
                
                auto split_result = StringUtils::split(test_str, "_");
                std::string join_result = StringUtils::join(split_result, "_");
                std::string upper_result = StringUtils::toUpper(test_str);
                std::string lower_result = StringUtils::toLower(upper_result);
                
                if (join_result == test_str && StringUtils::toLower(upper_result) == StringUtils::toLower(test_str)) {
                    success_count++;
                }
            }
        });
    }
    
    for (auto& thread : threads) {
        thread.join();
    }
    
    EXPECT_EQ(success_count.load(), num_threads * operations_per_thread);
    std::cout << "多线程安全性测试通过，成功操作: " << success_count.load() << " 次" << std::endl;
}

/*!
 * \brief 测试内存使用效率
 */
TEST_F(StringUtilsTest, TestMemoryEfficiency) {
    // 测试大量字符串操作不会导致内存泄漏
    const int iterations = 1000;
    
    for (int i = 0; i < iterations; ++i) {
        std::string base_str = "test_string_" + std::to_string(i);
        
        // 执行各种字符串操作
        auto split_result = StringUtils::split(base_str, "_");
        std::string join_result = StringUtils::join(split_result, "-");
        std::string trim_result = StringUtils::trim("  " + join_result + "  ");
        std::string replace_result = StringUtils::replace(trim_result, "test", "demo");
        std::string upper_result = StringUtils::toUpper(replace_result);
        
        // 验证结果正确性
        EXPECT_TRUE(StringUtils::startsWith(upper_result, "DEMO"));
    }
    
    std::cout << "内存效率测试通过，执行了 " << iterations << " 次字符串操作" << std::endl;
}

/*!
 * \brief 测试完整工作流程
 */
TEST_F(StringUtilsTest, TestCompleteWorkflow) {
    // 模拟一个完整的字符串处理工作流程
    std::string raw_data = "  APPLE,banana,Cherry;orange|grape  ";
    
    // 第一步：去除空白
    std::string trimmed = StringUtils::trim(raw_data);
    EXPECT_EQ(trimmed, "APPLE,banana,Cherry;orange|grape");
    
    // 第二步：标准化分隔符
    std::string normalized = StringUtils::replace(trimmed, ";", ",");
    normalized = StringUtils::replace(normalized, "|", ",");
    EXPECT_EQ(normalized, "APPLE,banana,Cherry,orange,grape");
    
    // 第三步：分割字符串
    auto fruits = StringUtils::split(normalized, ",");
    ASSERT_EQ(fruits.size(), 5);
    
    // 第四步：标准化大小写
    for (auto& fruit : fruits) {
        fruit = StringUtils::toLower(fruit);
    }
    
    // 第五步：重新组合
    std::string final_result = StringUtils::join(fruits, " | ");
    EXPECT_EQ(final_result, "apple | banana | cherry | orange | grape");
    
    // 第六步：添加前缀和后缀
    if (StringUtils::startsWith(final_result, "apple")) {
        final_result = "Fruits: " + final_result;
    }
    
    if (!StringUtils::endsWith(final_result, ".")) {
        final_result += ".";
    }
    
    EXPECT_EQ(final_result, "Fruits: apple | banana | cherry | orange | grape.");
    
    std::cout << "完整工作流程测试通过" << std::endl;
    std::cout << "处理结果: " << final_result << std::endl;
} 